<template>
  <div class="data-clean-tasks">
    <div class="page-header">
      <div class="header-left">
        <h2>数据清洗任务管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="fetchTaskList" style="margin-right: 10px;">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
        <el-button type="info" @click="goToBrandExtractor" style="margin-right: 10px;">
          <el-icon><MagicStick /></el-icon>前往品牌提取
        </el-button>
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>新建清洗任务
        </el-button>
      </div>
    </div>

    <!-- 任务列表 -->
    <div class="table-container">
      <div class="batch-actions" v-if="selectedTasks.length > 0">
        <el-button type="primary" @click="handleBatchClean" :disabled="!hasPendingTasks">
          <el-icon><Brush /></el-icon>批量清洗
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedTasks.some(task => task.status === 'processing')">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" >
          <el-icon><Delete /></el-icon>强删
        </el-button>
        <span class="selection-info">已选择 {{ selectedTasks.length }} 项</span>
      </div>
      
      <el-table
        v-loading="loading.table"
        :data="tasks"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="task_name" label="任务名称" min-width="150" />
        <el-table-column prop="source_type" label="数据来源" width="120">
          <template #default="{ row }">
            {{ getSourceTypeText(row.source_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="completed_at" label="完成时间" width="180">
          <template #default="{ row }">
            {{ row.completed_at ? formatDate(row.completed_at) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button 
                type="primary" 
                :disabled="row.status === 'processing'"
                @click="handleClean(row)"
              >
                <el-icon><Brush /></el-icon>{{ row.status === 'completed' ? '再次清洗' : '清洗' }}
              </el-button>
              <el-button 
                type="primary" 
                :disabled="row.status !== 'completed'"
                @click="downloadResult(row)"
              >
                <el-icon><Download /></el-icon>下载结果
              </el-button>
              <el-button 
                type="success" 
                :disabled="row.status !== 'completed'"
                @click="showStats(row)"
              >
                <el-icon><DataAnalysis /></el-icon>统计
              </el-button>
              <el-button 
                type="info" 
                :disabled="row.status !== 'completed'"
                @click="previewResult(row)"
              >
                <el-icon><View /></el-icon>预览
              </el-button>
              <el-button 
                type="danger" 
                :disabled="row.status === 'processing'"
                @click="handleDelete(row)"
              >
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 创建任务对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="创建数据清洗任务"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            :auto-upload="false"
            :limit="1"
            accept=".xlsx,.xls"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 xlsx/xls 文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 统计信息对话框 -->
    <el-dialog
      v-model="statsDialogVisible"
      title="数据统计信息"
      width="600px"
      destroy-on-close
    >
      <div v-loading="loading.stats">
        <template v-if="taskStats">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="任务名称">{{ taskStats.task_name }}</el-descriptions-item>
            <el-descriptions-item label="总商品数">{{ taskStats.total_products }}</el-descriptions-item>
            <el-descriptions-item label="识别品牌数">{{ taskStats.identified_brands }}</el-descriptions-item>
          </el-descriptions>
          
          <h4 class="stat-title">品牌分布</h4>
          <el-table
            :data="brandDistributionData"
            style="width: 100%"
            height="auto"
            max-height="200"
          >
            <el-table-column prop="brand" label="品牌" width="180" />
            <el-table-column prop="count" label="商品数" width="120" />
          </el-table>
          
          <h4 class="stat-title">单位分布</h4>
          <el-table
            :data="unitDistributionData"
            style="width: 100%"
            height="auto"
            max-height="200"
          >
            <el-table-column prop="unit" label="单位" width="180" />
            <el-table-column prop="count" label="商品数" width="120" />
          </el-table>
        </template>
        <template v-else-if="!loading.stats">
          <el-empty description="没有统计数据" />
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Download, Delete, Brush, DataAnalysis, Refresh, View, MagicStick
} from '@element-plus/icons-vue'
import {
  getDataCleanTasks,
  createDataCleanTask,
  deleteDataCleanTask,
  downloadFile,
  downloadTaskResult,
  cleanDataTask,
  getTaskStats,
} from '@/api/dataClean'
import { useRouter } from 'vue-router'

// 状态变量
const tasks = ref([])
const selectedTasks = ref([])
const uploadRef = ref(null)
const formRef = ref(null)
const dialogVisible = ref(false)
const taskStats = ref(null)
const statsDialogVisible = ref(false)
const refreshInterval = ref(null)

const form = ref({
  name: '',
  file: null
})

// 加载状态
const loading = reactive({
  table: false,
  submit: false,
  stats: false
})

// 表单验证规则
const rules = {
  name: [
    { required: false, message: '请输入任务名称', trigger: 'blur' }
  ],
  file: [
    { required: true, message: '请上传文件', trigger: 'change', validator: (rule, value, callback) => {
      if (!form.value.file) {
        callback(new Error('请上传文件'))
      } else {
        callback()
      }
    }}
  ]
}

const router = useRouter()

// 初始化
onMounted(() => {
  fetchTaskList()
  startAutoRefresh()
})

// 获取任务列表
const fetchTaskList = async () => {
  try {
    loading.table = true
    const data = await getDataCleanTasks()
    tasks.value = data
    
    // 检查是否有正在处理中的任务
    const hasProcessingTask = data.some(task => task.status === 'processing')
    
    // 如果有处理中的任务，确保自动刷新开启
    if (hasProcessingTask && !refreshInterval.value) {
      startAutoRefresh()
    } 
    // 如果没有处理中的任务，且自动刷新开启了，关闭自动刷新
    else if (!hasProcessingTask && refreshInterval.value) {
      stopAutoRefresh()
    }
    
    // 清空选中
    selectedTasks.value = []
  } catch (error) {
    console.error('获取数据清洗任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.table = false
  }
}

// 处理文件变更
const handleFileChange = (file) => {
  form.value.file = file.raw
  
  // 如果任务名称为空，则自动填充默认名称
  if (!form.value.name) {
    const fileName = file.name.replace(/\.[^/.]+$/, '') // 移除文件扩展名
    // 获取当前日期时间 格式：2025-04-13 14:30:00
    const currentDate = new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).replace(/\//g, '-').replace(/ /g, '_')
    form.value.name = `${fileName}_${currentDate}`
  }
}

// 处理文件移除
const handleFileRemove = () => {
  form.value.file = null
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.submit = true
        const formData = new FormData()
        
        // 如果没有输入任务名称，使用文件名+日期
        if (!form.value.name && form.value.file) {
          const fileName = form.value.file.name.replace(/\.[^/.]+$/, '')
          const currentDate = new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')
          form.value.name = `${fileName}_${currentDate}`
        }
        
        // 确保文件存在
        if (!form.value.file) {
          ElMessage.error('请选择文件')
          return
        }
        
        formData.append('name', form.value.name || form.value.file.name) // 确保name不为空
        formData.append('file', form.value.file)
        
        console.log('提交的表单数据：', {
          name: form.value.name || form.value.file.name,
          fileSize: form.value.file ? form.value.file.size : 'no file',
          fileName: form.value.file ? form.value.file.name : 'no file'
        })

        const result = await createDataCleanTask(formData)
        ElMessage.success('创建成功')
        dialogVisible.value = false
        fetchTaskList()
        // 重置表单
        formRef.value.resetFields()
        uploadRef.value.clearFiles()
      } catch (error) {
        console.error('创建任务失败:', error)
        let errorMessage = '创建任务失败'
        
        if (error.response) {
          if (error.response.status === 400) {
            errorMessage = `创建任务失败: ${error.response.data?.detail || '请检查文件格式'}`
          }
        }
        
        ElMessage.error(errorMessage)
      } finally {
        loading.submit = false
      }
    }
  })
}

// 处理创建按钮点击
const handleCreate = () => {
  form.value = {
    name: '',
    file: null
  }
  dialogVisible.value = true
}

// 删除任务
const handleDelete = async (task) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务 "${task.name}" 吗？相关的文件也将被删除。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteDataCleanTask(task.id)
    ElMessage.success('任务删除成功')
    fetchTaskList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除任务失败:', error)
      ElMessage.error('删除任务失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 下载结果文件
const downloadResult = async (task) => {
  // 移除对result_file_path的检查，改为检查任务状态
  if (task.status !== 'completed') {
    ElMessage.warning('任务未完成，无法下载结果')
    return
  }
  
  try {
    loading.table = true // 添加加载状态
    ElMessage.info('正在获取结果文件...')
    
    const response = await downloadTaskResult(task.id)
    console.log('》》》》》response.data:', response.data)
    console.log('》》》》》type:', Object.prototype.toString.call(response.data))
    
    // 这里应该用 response.data
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    
    // 获取文件名
    let filename = ''
    const contentDisposition = response.headers?.['content-disposition']
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename="(.+?)"/)
      if (filenameMatch && filenameMatch[1]) {
        filename = decodeURIComponent(filenameMatch[1])
      }
    }
    if (!filename && task.result_file_path) {
      filename = task.result_file_path.split('/').pop()
    }
    if (!filename) {
      filename = `${task.task_name || task.name || `任务${task.id}`}_清洗结果.xlsx`
    }
    
    // 创建下载链接
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    loading.table = false
  }
}

// 获取数据来源文本
const getSourceTypeText = (sourceType) => {
  const types = {
    'file': '文件',
    'database': '数据库'
  }
  return types[sourceType] || sourceType
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    'pending': 'info',
    'processing': 'warning',
    'completed': 'success',
    'failed': 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '等待处理',
    'processing': '处理中',
    'completed': '已完成',
    'failed': '失败'
  }
  return texts[status] || status
}

// 日期格式化
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 处理清洗按钮点击
const handleClean = async (task) => {
  try {
    await cleanDataTask(task.id)
    ElMessage.success('开始清洗数据')
    fetchTaskList() // 刷新列表
  } catch (error) {
    console.error('清洗数据失败:', error)
    ElMessage.error('清洗数据失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 获取统计信息
const showStats = async (task) => {
  statsDialogVisible.value = true
  taskStats.value = null
  loading.stats = true
  
  try {
    const data = await getTaskStats(task.id)
    // 使用nextTick等待DOM更新后再设置数据，避免ResizeObserver错误
    await nextTick()
    taskStats.value = data
    loading.stats = false
  } catch (error) {
    console.error('获取统计信息失败:', error)
    ElMessage.error('获取统计信息失败: ' + (error.response?.data?.detail || error.message))
    loading.stats = false
  }
}

// 计算属性
const brandDistributionData = computed(() => {
  if (!taskStats.value || !taskStats.value.brand_distribution) return []
  
  // 确保brand_distribution是一个对象
  const distribution = taskStats.value.brand_distribution || {}
  return Object.entries(distribution)
    .map(([brand, count]) => ({ 
      brand: brand || '未知', 
      count: count || 0 
    }))
    .filter(item => item.brand) // 过滤掉空品牌
    .sort((a, b) => b.count - a.count)
})

const unitDistributionData = computed(() => {
  if (!taskStats.value || !taskStats.value.units_distribution) return []
  
  // 确保units_distribution是一个对象
  const distribution = taskStats.value.units_distribution || {}
  return Object.entries(distribution)
    .map(([unit, count]) => ({ 
      unit: unit || '未知', 
      count: count || 0 
    }))
    .filter(item => item.unit) // 过滤掉空单位
    .sort((a, b) => b.count - a.count)
})

// 开始自动刷新
const startAutoRefresh = () => {
  stopAutoRefresh() // 先清除可能存在的计时器
  
  // 每10秒刷新一次
  refreshInterval.value = setInterval(() => {
    fetchTaskList()
  }, 10000)
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
    refreshInterval.value = null
  }
}

// 在组件卸载时清除定时器
onUnmounted(() => {
  stopAutoRefresh()
})

// 预览结果文件
const previewResult = (row) => {
  router.push(`/data-clean-result-preview/${row.id}`)
}

// 处理选择变化
const handleSelectionChange = (selected) => {
  selectedTasks.value = selected
}

// 批量删除任务
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量删除选中的 ${selectedTasks.value.length} 个任务吗？相关的文件也将被删除。`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }
    )
    
    // 逐个删除任务
    for (const task of selectedTasks.value) {
      await deleteDataCleanTask(task.id)
    }
    
    ElMessage.success('选中的任务已批量删除')
    fetchTaskList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除任务失败:', error)
      ElMessage.error('批量删除任务失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 批量清洗任务
const handleBatchClean = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量清洗选中的 ${selectedTasks.value.length} 个任务吗？`,
      '批量清洗确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'primary'
      }
    )
    
    // 逐个清洗任务
    for (const task of selectedTasks.value) {
      if (task.status !== 'processing') {
        await cleanDataTask(task.id)
      }
    }
    
    ElMessage.success('选中的任务已开始清洗')
    fetchTaskList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量清洗任务失败:', error)
      ElMessage.error('批量清洗任务失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 计算批量操作相关的状态
const hasPendingTasks = computed(() => {
  if (selectedTasks.value.length === 0) return false;
  return selectedTasks.value.some(task => 
    task.status !== 'processing'
  );
})

const hasCompletedTasks = computed(() => {
  if (selectedTasks.value.length === 0) return false;
  return selectedTasks.value.some(task => 
    task.status === 'completed'
  );
})

// 从
const goToBrandExtractor = () => {
  router.push('/brand-extractor')
}
</script>

<style scoped>
.data-clean-tasks {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.upload-demo {
  width: 100%;
}

.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
}

.stat-title {
  margin-top: 20px;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.selection-info {
  margin-left: 10px;
  font-size: 14px;
  color: #606266;
}
</style> 